package com.zhuiyun.educations.security.commonhandler;


import com.zhuiyun.educations.api.User.entity.User;
import com.zhuiyun.educations.api.sysUser.entiy.SysUser;
import com.zhuiyun.educations.api.sysUser.service.SysUserService;
import com.zhuiyun.educations.common.response.CommonResult;
import com.zhuiyun.educations.common.response.ResponseUtil;
import com.zhuiyun.educations.security.jwt.JWTConfig;
import com.zhuiyun.educations.security.jwt.JWTUtils;
import com.zhuiyun.educations.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

/**
 * @ClassName AuthenticationSuccessHandler
 * @Description 登录成功的操作
 * @Author zcy
 * @Date 2023/3/27 11:20
 **/
@Component
public class UserLoginAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    SysUserService sysUserService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        sysUser.setLastLoginTime(new Date());
//        sysUser.setUpdateTime(new Date());
//        // 获取登录ip
//        sysUser.setLastLoginIp(request.getLocalAddr());
//        sysUserService.updateUserByLogin(user);
        String token = JWTUtils.createAccessToken(user);
        // 设置token过期时间
        RedisUtil.set(token,user, JWTConfig.expiration);
        RedisUtil.set(user.getLoginName(),token,JWTConfig.expiration);
        token = JWTConfig.tokenPrefix + token;
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("avatarUrl",user.getAvatarUrl());
        hashMap.put("token", token);
        hashMap.put("userId", user.getId());
        hashMap.put("userName",user.getUserName());
        // 将token 放入redis中
        ResponseUtil.responseJson(response, CommonResult.ok(hashMap));
    }
}
